﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using AndreySmirnov.BLToolkitUtils.VSPackage.Model;

namespace AndreySmirnov.BLToolkitUtils.VSPackage
{
    public static class CredentialHelpers
    {
        public const string USER_NAME_KEY = "User Id";
        public const string PASSWORD_KEY = "Password";

        public static string ParseConnectionData(string credentialsData, string valName)
        {
            //User Id=AsmiTechWebSite;Password=AsmiTechWebSitePass
            var values = credentialsData.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
            var dict = values.Select(s => s.Split(new[] {"="}, StringSplitOptions.RemoveEmptyEntries))
                .Where(parts => parts.Length == 2)
                .ToDictionary(parts => parts[0].Trim(), parts => parts[1].Trim());
            if (!dict.ContainsKey(valName))
                return String.Empty;
            return dict[valName];
        }

        public static string FormatConnectionString(this BLTConnectionInfo connectionInfo)
        {
            switch (connectionInfo.CredentialsType)
            {
                case BLTConnectionCredentialsType.ClearText:
                    {
                        var userName = ParseConnectionData(connectionInfo.CredentialsData, USER_NAME_KEY);
                        var password = ParseConnectionData(connectionInfo.CredentialsData, PASSWORD_KEY);
                        return string.Format("Server={0};Initial Catalog={1};User Id={2};Password={3}",
                                             connectionInfo.Server,
                                             connectionInfo.DatabaseName,
                                             userName,
                                             password);
                    }
                case BLTConnectionCredentialsType.Encrypted:
                    throw new NotImplementedException("Not yet implemented");
                    break;
                case BLTConnectionCredentialsType.Prompt:
                    throw new NotImplementedException("Not yet implemented");
                    break;
                case BLTConnectionCredentialsType.SSPI:
                    {
                        return string.Format("Server={0};Initial Catalog={1};Integrated Security=SSPI;",
                                             connectionInfo.Server,
                                             connectionInfo.DatabaseName);
                    }
                default:
                    throw new ArgumentOutOfRangeException();
            }
        }
    }
}
